/*
 * Copyright (C) 2016 Baidu, Inc. All Rights Reserved.
 */
package me.cuilei.springbootdemo;

import static org.mockito.BDDMockito.given;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.RequestBuilder;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;

import me.cuilei.springbootdemo.user.AdminConfig;
import me.cuilei.springbootdemo.user.User;
import me.cuilei.springbootdemo.user.UserController;
import me.cuilei.springbootdemo.user.UserRepository;

/**
 * Created by cuilei05 on 16/9/29.
 */
@RunWith(SpringRunner.class)
@WebMvcTest(UserController.class)
public class UserControllerTestsWithMockMvc {
    @Autowired
    private MockMvc mockMvc;

    @MockBean
    private UserRepository userRepository;

    @MockBean
    private AdminConfig adminProperties;

    @Test
    public void testGetByUserId() throws Exception {
        // Mock userRepository
        given(userRepository.findByUserId(1L)).willReturn(new User(1L, "小明"));

        // 构建WEB请求
        RequestBuilder getUserByIdRequest = MockMvcRequestBuilders.get("/user/1")
                .accept(MediaType.APPLICATION_JSON_UTF8);

        /**
         *执行请求并添加如下操作:
         * 1 打印http请求和响应
         * 2 判断http响应是否OK
         * 3 判断响应contentType是否是json格式
         * 4 使用jsonPath判断响应内容是否符合要求
         **/
        mockMvc.perform(getUserByIdRequest)
                .andDo(print())
                .andExpect(status().isOk())
                .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8))
                .andExpect(jsonPath("$.userId").value(1))
                .andExpect(jsonPath("$.userName").value("小明"));
    }
}
